<?php

require_once 'Connection.php';

class Login {

    public $conn;

    function __construct() {
        $con = new Connection();
        $this->conn = $con->configDB();
    }

    //Player
    function checkLogin() {
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];
        $passwordENC = md5($password . $this->getSaltLogin($username)) . base64_decode($this->getSaltLogin($username));
        $result = $this->login($username, $passwordENC);
        return $result;
    }

    function login($username, $password) {
        $select = "SELECT p.PlayerID, p.IsLocked, p.Role " .
                "FROM players p JOIN playerbalance pb ON p.PlayerID = pb.PlayerID " .
                "WHERE p.Username = '$username' AND p.`Password` = '$password' AND p.Role = 0";
        $query = mysqli_query($this->conn, $select);
        $num = mysqli_num_rows($query);
        $userLog = array();
        // player login successfull
        if ($num > 0) {
            while ($row = mysqli_fetch_array($query)) {
                $userLog['PlayerID'] = $row['PlayerID'];
                $userLog['Role'] = $row['Role'];
                $userLog['isLocked'] = $row['IsLocked'];
            }
            //update login time
            $this->updateLoginTime($username);
        }
        // player login failed
        else {
            $userLog = NULL;
        }
        return $userLog;
    }

    //Agent
    function checkLoginAgent() {
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];
        $passwordENC = md5($password . $this->getSaltLogin($username)) . base64_decode($this->getSaltLogin($username));
        $result = $this->loginAgent($username, $passwordENC);
        return $result;
    }

    function loginAgent($username, $password) {
        $select = "SELECT p.PlayerID, p.IsLocked, p.Role " .
                "FROM players p JOIN playerbalance pb ON p.PlayerID = pb.PlayerID " .
                "WHERE p.Username = '$username' AND p.`Password` = '$password' AND p.Role > 0";
        $query = mysqli_query($this->conn, $select);
        $num = mysqli_num_rows($query);
        $agentLog = array();
        // player login successfull
        if ($num > 0) {
            while ($row = mysqli_fetch_array($query)) {
                $agentLog['PlayerID'] = $row['PlayerID'];
                $agentLog['Role'] = $row['Role'];
                $agentLog['isLocked'] = $row['IsLocked'];
            }
            //update login time
            $this->updateLoginTime($username);
        }
        // player login failed
        else {
            $agentLog = NULL;
        }
        return $agentLog;
    }

    function getSaltLogin($username) {
        $select = "select Salt from players where Username = '$username'";
        $query = mysqli_query($this->conn, $select);
        $row = mysqli_fetch_array($query);
        return $row["Salt"];
    }

    function getPlayerLogonInfor($playerID) {
        $select = "SELECT p.PlayerID, p.Username, p.Email, p.IsLocked, p.Role, pb.BMoney, pi.* " .
                "FROM players as p LEFT JOIN playerbalance as pb " .
                "ON p.PlayerID = pb.PlayerID " .
                "LEFT JOIN playerinformation as pi " .
                "ON pi.PlayerID = p.PlayerID " .
                "WHERE p.PlayerID = $playerID";
        $query = mysqli_query($this->conn, $select);
        $rows = mysqli_fetch_array($query);
        return $rows;
    }

    function checkOldPasswordPlayer($playerID) {
        $passwordTyp = $_REQUEST['oldPassword'];
        $select = "select `Password`, Salt from players where PlayerID = $playerID";
        mysqli_query($this->conn, "SET NAMES 'utf8'");
        $query = mysqli_query($this->conn, $select);
        $row = mysqli_fetch_assoc($query);
        $salt = base64_decode($row["Salt"]);
        $saltEnc = base64_encode($salt);
        $passEnc = md5($passwordTyp . $saltEnc) . $salt;
        return ($row["Password"] == $passEnc) ? TRUE : FALSE;
    }

    function updateNewPasswordPlayer($playerID) {
        $password = $_REQUEST['newPassword'];
        $functions = new Functions();
        $salt = $functions->generateString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890", 8);
        $saltEnc = base64_encode($salt);
        $passEnc = md5($password . $saltEnc) . $salt;
        $strUpdate = "update players set `Password` = '$passEnc', Salt = '$saltEnc' where PlayerID = $playerID ";
        $updateQuery = mysqli_query($this->conn, $strUpdate);
        return $updateQuery;
    }

    function getPlayerBetHistory($playerID) {
        $playerBetHistoryDateFrom = $_REQUEST['playerBetHistoryDateFrom'];
        $playerBetHistoryDateTo = $_REQUEST['playerBetHistoryDateTo'];
        mysqli_query($this->conn, "SET NAMES 'utf8'");
        $filterQ = ($playerBetHistoryDateFrom == "" && $playerBetHistoryDateTo == "") ? "" : " and (b.BetDate BETWEEN '$playerBetHistoryDateFrom' and '$playerBetHistoryDateTo')";
        $select = "select r.`Name` AS Mien,h.`Name` AS Loai,p.`Name` AS Tinh,b.BetNumber,b.BetMoney,b.BetDate,b.WinTimes,b.Pendding "
                . "from provinces p join betthreads b on p.ProvinceID = b.ProvinceID  "
                . "join subthreadrule s on b.SubThreadRuleID = s.SubThreadRuleID "
                . "join regions r on s.RegionID = r.RegionID "
                . "join subthreads h on h.SubThreadID = s.SubThreadID "
                . "where b.PlayerID=$playerID" . $filterQ . " LIMIT 10";

        $query = mysqli_query($this->conn, $select);
        $arr = array();
        while ($row = mysqli_fetch_assoc($query)) {
            array_push($arr, $row);
        }
        return $arr;
    }

    //update login time
    function updateLoginTime($username) {
        date_default_timezone_set("Asia/Ho_Chi_Minh");
        $currentTime = date("Y-m-d H:i:s");
        $strUpdate = "UPDATE players SET LastLogin = '$currentTime' WHERE Username = '$username'";
        $strQuery = mysqli_query($this->conn, $strUpdate);
        return $strQuery;
    }

}
